package com.maori.languageapp.curate.songs;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.LanguageAppCaptureActivity;
import com.maori.languageapp.R;
import com.maori.languageapp.consts.JSONfunctions;
import com.maori.languageapp.consts.UrlContant;
import com.maori.languageapp.subview.Maori_BookMark_Items;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class Maori_Curate_Song extends Activity {

	TextView txtHeading;
	ProgressDialog mProgressDialog;
	String getDiscoverWordsListURL, LastDownloadUpdateTime, BookMarkRefId,
			result, node_category;
	JSONObject jsonobject, jsonobjectres;
	JSONArray jsonarray;
	ListView listview;
	int NCMID;
	int timeoutConnection = 5000;
	InputStream is = null;
	StringBuilder sb = null;
	JSONArray jArray;
	HttpParams httpParameters = new BasicHttpParams();
	Maori_Curate_Song_Adapter adapter;
	ArrayList<HashMap<String, String>> arraylist;
	LinearLayout checkemptylist, listingNodeDetails;
	Button navigateToCapture;
	int listCounter = 0;
	int NodeAudioPlay = 0;
	private MediaPlayer mediaPlayer;
	String CurrentUID,AudioURL;
	/************ Adapter Constant Variables ****************/
	static String MID = "MID";
	static String NID = "NID";
	static String word = "word";
	static String wordcontent = "wordcontent";
	static String wordb = "wordb";
	static String wordcontentb = "wordcontentb";
	static String M_Source = "M_Source";
	static String NCMIDStr = "NCMIDStr";
	static String first_name = "first_name";
	static String last_name = "last_name";
	static String tribe = "tribe";
	static String userimage = "userimage";

	static String TotalsLikes = "TotalsLikes";
	static String TotalsSynonim = "TotalsSynonim";
	static String TotalImages = "TotalImages";
	static String TotalAudios = "TotalAudios";
	static String TotalVideos = "TotalVideos";

	private static String UserNodeBookMarked = "UserNodeBookMarked";
	private static String node_dif_audio_url = "node_dif_audio_url";
	private static String MAINUID = "MAINUID";
	private static String UserLikedForNode = "UserLikedForNode";
	
	//************Curate State****************
	private static String NodeCurateState = "NodeCurateState";
	private static String NodeApprovalCount = "NodeApprovalCount";
	private static String NodeRejectedCount = "NodeRejectedCount";
	
	private SQLiteDatabase mydb;
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private static final String TAG = null;
	
	// navigateToCapture
	public void navigateToCapture(View view) {
		Intent i = new Intent(getApplicationContext(),
				LanguageAppCaptureActivity.class);
		int MEDIAID = Integer.parseInt(NCMIDStr);
		i.putExtra("NCMID", MEDIAID);
		i.putExtra("node_category", node_category);
		i.putExtra("type", "Song");
		i.putExtra("SEARCHKEY", "00/00/00/00/00");
		i.putExtra("ACTIVE", "1");
		startActivity(i);
	}
	
	public void btnBackAction(View view) {
		Maori_Curate_Song.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}
	@Override
	public void onBackPressed() {
		Maori_Curate_Song.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}
	public void PlayDefaultAudio(View view) {
		Button des = (Button) view;
		AudioURL = des.getText().toString();
	
		if(NodeAudioPlay == 0){
			NodeAudioPlay = 1;
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			try {
				mediaPlayer.setDataSource(AudioURL);
				mediaPlayer.prepare();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			mediaPlayer.start();
			Log.e("########", "Audio Recording Play Start...");
			// Audio Complete Identification
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				public void onCompletion(MediaPlayer mp) {
					mediaPlayer.stop();
					mediaPlayer.reset();
					NodeAudioPlay = 0;
					Log.e("########", "Audio Play Completed...");
				}
			});
		}
		
		
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Remove title bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.maori_discover_list_panel);

		txtHeading = (TextView) findViewById(R.id.screenTitle);
		txtHeading.setText("Curate Song");
		/********** Calling URL *************/
		getDiscoverWordsListURL = UrlContant.getDiscoverWordsList;

		checkemptylist = (LinearLayout) findViewById(R.id.checkemptylist);
		listingNodeDetails = (LinearLayout) findViewById(R.id.listingNodeDetails);
		navigateToCapture = (Button) findViewById(R.id.navigateToCapture);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			NCMIDStr = extras.getString("NCMID");
			node_category = extras.getString("node_category");
		}
		
		
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterUserInfo = new ContentValues();
		Cursor readUserDetails = null;
		try {
			String queryCheckUsers = "SELECT * FROM User Where Activate = '1'";
			readUserDetails = mydb.rawQuery(queryCheckUsers, null);
		} catch (Exception e) {

		}
		if (readUserDetails != null) {
			if (readUserDetails.getCount() > 0) {
				while (readUserDetails.moveToNext()) {
					CurrentUID = readUserDetails.getString(11);
				}
			}
			else{
				CurrentUID = "1";
			}
		}
		mydb.close();

		new DownloadJSON().execute();
	}

	// DownloadJSON AsyncTask
	private class DownloadJSON extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(Maori_Curate_Song.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Loading");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Songs Details..");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/curate/getFilteredCurateSongs.php");
				JSONObject json = new JSONObject();
				json.put("record1", NCMIDStr);
				json.put("record2", CurrentUID);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request MID**** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "PRINT WORDS = " + result);
						arraylist = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							for (int i = 0; i < jsonarray.length(); i++) {
								JSONObject c = jsonarray.getJSONObject(i);
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("word", c.getString("word"));
								map.put("wordcontent",
										c.getString("wordcontent"));
								map.put("wordb", c.getString("wordb"));
								map.put("wordcontentb",
										c.getString("wordcontentb"));
								map.put("NID", c.getString("NID"));
								map.put("M_Source", c.getString("M_Source"));
								map.put("MID", c.getString("MID"));
								map.put("first_name", c.getString("first_name"));
								map.put("last_name", c.getString("last_name"));
								map.put("tribe", c.getString("tribe"));
								map.put("userimage", c.getString("userimage"));
								map.put("TotalsLikes",
										c.getString("TotalsLikes"));
								map.put("TotalsSynonim",
										c.getString("TotalsSynonim"));
								map.put("TotalImages",
										c.getString("TotalImages"));
								map.put("TotalAudios",
										c.getString("TotalAudios"));
								map.put("TotalVideos",
										c.getString("TotalVideos"));
								
								map.put("UserNodeBookMarked", c.getString("UserNodeBookMarked"));
								map.put("node_dif_audio_url", c.getString("node_dif_audio_url"));
								map.put("UserLikedForNode", c.getString("UserLikedForNode"));
								map.put("MAINUID", c.getString("MAINUID"));
								map.put("NodeCurateState", c.getString("NodeCurateState"));
								map.put("NodeApprovalCount", c.getString("NodeApprovalCount"));
								map.put("NodeRejectedCount", c.getString("NodeRejectedCount"));
								// Set the JSON Objects into the array
								arraylist.add(map);
								listCounter = listCounter + 1;
							}
						} catch (Exception e) {
							Log.v(TAG, "***** Exception *****:" + e);
						}
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			if (listCounter >= 1) {
				listingNodeDetails.setVisibility(LinearLayout.VISIBLE);
				checkemptylist.setVisibility(LinearLayout.GONE);
				// Locate the listview in listview_main.xml
				listview = (ListView) findViewById(R.id.listviewdiscover);
				// Pass the results into ListViewAdapter.java
				adapter = new Maori_Curate_Song_Adapter(
						Maori_Curate_Song.this, arraylist);
				// Binds the Adapter to the ListView
				listview.setAdapter(adapter);
				// Close the progressdialog
			} else {
				listingNodeDetails.setVisibility(LinearLayout.GONE);
				checkemptylist.setVisibility(LinearLayout.VISIBLE);
				navigateToCapture.setText("No Records Found In This Category");
				navigateToCapture.setCompoundDrawablesWithIntrinsicBounds(0, 0,
						0, R.drawable.capture_songs);
			}
			mProgressDialog.dismiss();
		}
	}

	// ***********Memory Handling****************
	@Override
	protected void onStop() {
		super.onStop();
	}

	// Fires after the OnStop() state
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			trimCache(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void trimCache(Context context) {
		try {
			File dir = context.getCacheDir();
			if (dir != null && dir.isDirectory()) {
				deleteDir(dir);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}
	
	/****************Getters and Setters*****************************/
	public static String getWord() {
		return word;
	}

	public static void setWord(String word) {
		Maori_Curate_Song.word = word;
	}

	public static String getWordb() {
		return wordb;
	}

	public static void setWordb(String wordb) {
		Maori_Curate_Song.wordb = wordb;
	}

	public static String getTotalsSynonim() {
		return TotalsSynonim;
	}

	public static void setTotalsSynonim(String totalsSynonim) {
		TotalsSynonim = totalsSynonim;
	}

	public static String getTotalAudios() {
		return TotalAudios;
	}

	public static void setTotalAudios(String totalAudios) {
		TotalAudios = totalAudios;
	}

	public static String getTotalImages() {
		return TotalImages;
	}

	public static void setTotalImages(String totalImages) {
		TotalImages = totalImages;
	}

	public static String getTotalVideos() {
		return TotalVideos;
	}

	public static void setTotalVideos(String totalVideos) {
		TotalVideos = totalVideos;
	}

	public static String getTotalsLikes() {
		return TotalsLikes;
	}

	public static void setTotalsLikes(String totalsLikes) {
		TotalsLikes = totalsLikes;
	}

	public static String getUserNodeBookMarked() {
		return UserNodeBookMarked;
	}

	public static void setUserNodeBookMarked(String userNodeBookMarked) {
		UserNodeBookMarked = userNodeBookMarked;
	}

	public static String getNode_dif_audio_url() {
		return node_dif_audio_url;
	}

	public static void setNode_dif_audio_url(String node_dif_audio_url) {
		Maori_Curate_Song.node_dif_audio_url = node_dif_audio_url;
	}

	public static String getM_Source() {
		return M_Source;
	}

	public static void setM_Source(String m_Source) {
		M_Source = m_Source;
	}

	public static String getNID() {
		return NID;
	}

	public static void setNID(String nID) {
		NID = nID;
	}

	public static String getMID() {
		return MID;
	}

	public static void setMID(String mID) {
		MID = mID;
	}

	public static String getFirst_name() {
		return first_name;
	}

	public static void setFirst_name(String first_name) {
		Maori_Curate_Song.first_name = first_name;
	}

	public static String getLast_name() {
		return last_name;
	}

	public static void setLast_name(String last_name) {
		Maori_Curate_Song.last_name = last_name;
	}

	public static String getTribe() {
		return tribe;
	}

	public static void setTribe(String tribe) {
		Maori_Curate_Song.tribe = tribe;
	}

	public static String getUserimage() {
		return userimage;
	}

	public static void setUserimage(String userimage) {
		Maori_Curate_Song.userimage = userimage;
	}

	public static String getMAINUID() {
		return MAINUID;
	}

	public static void setMAINUID(String mAINUID) {
		MAINUID = mAINUID;
	}

	public static String getUserLikedForNode() {
		return UserLikedForNode;
	}

	public static void setUserLikedForNode(String userLikedForNode) {
		UserLikedForNode = userLikedForNode;
	}
	public static String getNodeCurateState() {
		return NodeCurateState;
	}

	public static void setNodeCurateState(String nodeCurateState) {
		NodeCurateState = nodeCurateState;
	}

	public static String getNodeApprovalCount() {
		return NodeApprovalCount;
	}

	public static void setNodeApprovalCount(String nodeApprovalCount) {
		NodeApprovalCount = nodeApprovalCount;
	}

	public static String getNodeRejectedCount() {
		return NodeRejectedCount;
	}

	public static void setNodeRejectedCount(String nodeRejectedCount) {
		NodeRejectedCount = nodeRejectedCount;
	}
}
